﻿#region Using Directives

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    using MarketPulse.BusinessLogic.Common;
    using MarketPulse.BusinessLogic.Common.Criteria;

    using MarketPulse.BusinessLogic.Private;

    using MarketPulse.Web.Helpers;

#endregion

namespace MUM.Controllers
{
    /// <summary>
    /// Controller used to handle all actions for Assignment processing
    /// </summary>
    [HandleError]
    public class AssignmentController : MarketPulse.Web.Mvc.Controller
    {
        #region Member Variables

            /// <summary>
            /// String used to hold the view path to use for returning from an action (when there is more than one view depending on logic)
            /// </summary>
            private string mViewPath;

            private const string constErrorMessage = "Ooops! I'm afraid an unforseen error occurred. Please report this error, along with a detailed description of what you were doing, to the IT department.";

        #endregion

        #region Methods

            #region Exposed Controller Methods

                [AcceptVerbs(HttpVerbs.Get)]
                public ActionResult Index()
                {
                    // redirect the index to the list action
                    return RedirectToAction("Search");
                }

                /// <summary>
                /// Method used to handle a post to the Search action for this controller
                /// </summary>
                /// <returns>An action result object</returns>
                [AcceptVerbs(HttpVerbs.Post)]
                public ActionResult GetResults(FormCollection form)
                {
                    AssignmentSearchCriteria criteria;
                    try
                    {
                        if (SessionManager.AssignmentSearchCriteria != null)
                        {
                            criteria = SessionManager.AssignmentSearchCriteria;
                        }
                        else
                        {
                            criteria = new AssignmentSearchCriteria(null, Guid.Parse(form["country"]));

                            SessionManager.AssignmentSearchCriteria = criteria;
                        }
                        GetAssignmentSearchResults(criteria);
                    }
                    catch (Exception ex)
                    {
                        mLog.Error("Exception experienced whilst processing the 'List' action of the 'Assignment' Controller", ex);
                        ViewBag.Message = constErrorMessage;
                        RedirectToAction("Index", "Home");
                        //mViewPath = "~/Views/Home";
                    }
                    return View(mViewPath);
                }

                #region Search & Results

                    /// <summary>
                    /// Method used to handle a get to the Get Results action for this controller
                    /// </summary>
                    /// <returns>An action result object</returns>
                    [AcceptVerbs(HttpVerbs.Get)]
                    public ActionResult GetResults()
                    {
                        try
                        {
                            GetAssignmentSearchResults(SessionManager.AssignmentSearchCriteria);
                        }
                        catch (Exception ex)
                        {
                            mLog.Error("Exception experienced whilst processing the 'List' action of the 'Assignment' Controller", ex);
                            ViewBag.Message = constErrorMessage;
                            RedirectToAction("Index", "Home");
                            //mViewPath = "~/Views/Home";
                        }
                        return View(mViewPath);
                    }

                #endregion

                #region Assign

                    [AcceptVerbs(HttpVerbs.Post)]
                    public PartialViewResult ChangeAssignment(Guid assignmentGuid, long assignmentVersionId)
                    {
                        ViewBag.Assignment = Assignment.GetByGuidAndVersionId(assignmentGuid, assignmentVersionId);
                        ViewBag.PaymentTypeInfoList = PaymentTypeInfoList.GetAll();
                        ViewBag.Shoppers = UserInfoList.GetByCountryGuidAndUserRoleGuid(SessionManager.AssignmentSearchCriteria.CountryGuid.Value, Guid.Parse(ConfigurationManager.AppSettings["MysteryShopperRoleGuid"]));
                        return PartialView("~/Views/Assignment/Partials/_ChangeAssignment.cshtml");
                    }

                    /// <summary>
                    /// Method used to handle a post to the UpdateAssignment action
                    /// </summary>
                    /// <param name="form">The serialized form objet from the view that initiated the post</param>
                    /// <returns>An action result object</returns>
                    [AcceptVerbs(HttpVerbs.Post)]
                    public ActionResult UpdateAssignment(FormCollection form)
                    {
                        try
                        {
                            Assignment assigment = Assignment.GetByGuidAndVersionId(Guid.Parse(form["AssignmentGuid"]), Int64.Parse(form["AssignmentVersionId"]));
                            assigment.Assign(Guid.Parse(form["assignedUser"]), DateTime.Parse(form["plannedDate"] + " " + form["timelist"]));

                            foreach (var payment in assigment.Payments)
                            {
                                if (form[payment.GUID.ToString()] != "")
                                {
                                    payment.Amount = Double.Parse(form[payment.GUID.ToString()]);
                                }
                            }

                            assigment.Save();

                            GetAssignmentSearchResults(SessionManager.AssignmentSearchCriteria);
                            ViewBag.Message = "Assignment " + form["AssignmentGuid"] + " allocated to user";
                            ViewBag.PartialPath = "~/Views/Assignment/Partials/_SearchResults.cshtml";
                            mViewPath = "~/Views/Shared/Results.cshtml";
                        }
                        catch (Exception ex)
                        {
                            mLog.Error("Exception experienced whilst processing the 'UpdateAssignment' action of the 'Assignment' Controller", ex);
                            ViewBag.Message = constErrorMessage;
                            RedirectToAction("Index", "Home");
                        }
                        return View(mViewPath);
                    }

                #endregion

            #endregion

            #region Local Methods

                /// <summary>
                /// Method used to set up the call back for the results for a search for Assignment records
                /// </summary>
                /// <param name="criteria">The criteria to use to as part of the search</param>
                private void GetAssignmentSearchResults(AssignmentSearchCriteria criteria)
                {
                    if (criteria != null)
                    {
                        // Reload the country list
                        var countryList = SessionManager.AvailableCountries;
                        ViewBag.CountryInfoList = countryList;

                        if (!criteria.CountryGuid.Equals(Guid.Empty))
                        {
                            // Get the results  
                            var assignmentInfoList = AssignmentList.GetByCountryGuid(criteria.CountryGuid.Value);

                            // If no results are returned stay on the search page
                            if (assignmentInfoList.Count > 0)
                            {
                                ViewBag.AssignmentInfoList = assignmentInfoList;
                                ViewBag.Message = assignmentInfoList.Count + " Assignments found using your search criteria";
                                ViewBag.PartialPath = "~/Views/Assignment/Partials/_SearchResults.cshtml";
                                mViewPath = "~/Views/Shared/Results.cshtml";
                            }
                            else
                            {
                                //ViewBag.NoResults = true;
                                SessionManager.AssignmentSearchCriteria = null;
                                ViewBag.Message = "No Assignments Found for Country - " + countryList.FindByGuid(criteria.CountryGuid.Value).CountryName;
                                RedirectToAction("Index", "Home");
                                //mViewPath = "~/Views/Home";
                            }
                        }
                    }
                }

            #endregion

        #endregion

    }
}
